
new Vue({
	el:'#orderPage',
	data(){

		return {
			openId:'',
			originator: true,
			name: '',
			mobile: '',
			contactLocation:'',
			userInfo: {},
			loading:false,
			groupOrderId:null,

			//课程
			courseTitle: '',
			courseId: '',
			courseItems: [
				{ 'name': 'Wonders--启蒙班', id: 10001 ,people:'（2～4人）' ,detail:'适合英语零基础的孩子'},
				{ 'name': 'Wonders--基础班', id: 10002 ,people:'（2～4人）' ,detail:'适合已有一年左右英语学习基础的孩子'},
				{ 'name': 'Wonders--进阶班', id: 10003 ,people:'（2～4人）' ,detail:'适合已有两年及以上英语学习基础的孩子'},
			],
			couresContactName:'',
			couresLocation:'',
			couresAddress: '',

			//组团人数
			people: [2,3,4,5],
			peopleIndex: 0,

			//可选时间
			tryTimeArr: [
				{ keyName: 'WORKDAY_DAY', text: '工作日白天 10:00~18:00', checked: false},
				{ keyName: 'WORKDAY_NIGHT', text: '工作日晚上 18:00~19:00', checked:false},
				{ keyName: 'WEEKEND_DAY', text: '双休日白天 10:00~18:00', checked: false},
				{ keyName: 'WEEKEND_NIGHT', text: '双休日晚上 18:00~19:00', checked: false },
			],
			tryTime: [],

			//备注说明
			comments: '',
			//提供场地
			hasSpace:false,
			locationConfirm:false,
			locationList:[],
			changeLocation: '',
			showSearch:false,

			amount: 0,
			orderId: '',
			allowOtherJoin: false, //是否允许附近其他小朋友参加我发起的拼班
		}
	},
	methods:{
		getUrlData(dataName){
			function getUrlVars(){ 
        var vars = {}, hash; 
        var href = window.location.href.split('#')[0];
        var hashes = href.slice(href.indexOf('?')+1).split('&'); 
        for(var i = 0; i < hashes.length; i++) { 
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1]?hash[1]:'';
        } 
        return vars; 
			} 
			var params = getUrlVars(); 
			
			for(var key in params){
					if(key == dataName){ 
							return params[key];
					}
			};
			return '';
		},

		//选择课程
		courseChange(id){
			this.courseId = id;
		},
		getCourseName(courseId){
			var courseItems = this.courseItems;
			for (var i = 0; i < courseItems.length;i++){
				if (courseItems[i].id == courseId){
					return courseItems[i].name;
				}
			}
		},
		//查看课程详情
		courseDetail(id){
			console.log(id);
		},
		//选择组团人数
		bindPeopleChange(e){
			this.peopleIndex = e.target.value
		},
		changeTime(index){
			var newData = JSON.parse(JSON.stringify(this.tryTimeArr));
			var checkNum = 0;
			for (var i = 0; i < newData.length;i++){
				if (newData[i].checked){
					checkNum++;
				}
			};
			
			// if (checkNum > 1 && !newData[index].checked){
			//   return;
			// }
	
			
			newData[index].checked = !newData[index].checked;
			this.tryTimeArr = newData
	
			var tryTimeArr = this.tryTimeArr;
			var newTime = [];
			for (var i = 0; i < tryTimeArr.length; i++) {
				if (tryTimeArr[i].checked) {
					newTime.push(tryTimeArr[i].keyName);
				}
			}
			this.tryTime = newTime;
		},
		hasSpaceChange(e){
			this.hasSpace = !this.hasSpace
		},
		bindName(e) {
			this.name = e.target.value
		},
		bindMobile(e) {
			this.mobile = e.target.value
		},
		bindComments(e){
			this.comments = e.target.value
		},
		//创建团
		createGroup(){
			var self = this;
	
			if (!self.courseId) {
				guigu.showModal({
					content: '请选择体验课程',
					showCancel: false
				});
			}else if (self.name == ''){
				guigu.showModal({
					content: '请填写联系人',
					showCancel: false
				});
			}else if (!/^1\d{10}$/.test(self.mobile)){
				guigu.showModal({
					content: '请填写正确的联系电话',
					showCancel: false
				});
			}else if(!self.contactLocation){
				guigu.showModal({
					content: '请填写城市和小区名称',
					showCancel: false
				});
			}
			// else if (self.tryTime.length < 2) {
			// 	guigu.showModal({
			// 		content: '请选择2项您最方便试听的时间',
			// 		showCancel: false
			// 	});
			// }
			else{
				// 极端情况处理，如果用户没有同意授权地址，仍选我的位置，则弹出提示
				if(self.contactLocation === self.changeLocation.cityname) {
					guigu.showModal({
						content: '由于您没有授权位置服务，我们无法获取您的位置信息，这将严重影响其他人加入您的拼班，建议您选择一个具体的地点或授权后再使用“我的位置',
						showCancel: true,
						okText:'重新选择',
						cancelText:'我要继续',
						cancelGray:true,
						okFn:function(){
							self.contactLocation = '';
							self.locationFocus();
						},
						cancelFn: function () {
							self.createNow();
						}
					});
					return;
				}

				self.createNow();

			}
		},
		createNow(){
			var self = this;

				//检测并开启loading
				guigu.showLoading({
					title: '数据加载中',
					mask: true
				});
				$.ajax({
					url: 'https://api.svenglish.cn/api/order/group',
					type: 'PUT',
					contentType: 'application/json',
					data: JSON.stringify({
						"courseId": this.courseId,
						"visibility": this.allowOtherJoin
					}),
					success:function(data){
						//关闭loading
						guigu.hideLoading();

						if (data.code==1) {
							self.groupOrderId = data.data.groupOrderId
							self.addGroup();

							//创建团的时候,微信外部浏览器记录本地创建的团单。用于其他页面判断是否发起人
							if(!self.isWeiXin()){
								var createGroupOrderIds = localStorage.getItem('createGroupOrderIds');
								if(createGroupOrderIds){
									createGroupOrderIds += ','+self.groupOrderId;
								}else{
									createGroupOrderIds = self.groupOrderId;
								};
								localStorage.setItem('createGroupOrderId',createGroupOrderIds);
							}

						}else{

							guigu.showModal({
								content: data.msg,
								showCancel: false
							});
						}
					},
					fail(res) {
						//关闭loading
						guigu.hideLoading();
						guigu.showModal({
							content: JSON.stringify(res),
							showCancel: false
						});
					}
				});

		},
		//加入团
		addGroup(){
			var self = this;
			
			var putData = {
				"groupOrderId": this.groupOrderId,
				"openId": this.openId,
				"originator": this.originator,  //是否发起人
				"courseId": this.courseId,  //课程ID
				"provideTime": this.tryTime.join(','),
				"contactName": this.name,
				"contactPhone": this.mobile,
				"contactLocation": this.contactLocation,
				"amount": this.amount,  //价格
				"comments": this.comments,
				"provideSpace": !this.hasSpace,
				"locationCity": this.changeLocation.cityname,
				// "locationDistrict": this.changeLocation.district,
				"locationLatitude": this.changeLocation.latlng.lat,
				"locationLongitude": this.changeLocation.latlng.lng,
				// "locationProvince": this.changeLocation.province,
				"locationAddress": this.changeLocation.poiaddress
			};


			// 判断是否是从附近拼班过来的 就带上source参数
			var stranger = this.getUrlData('stranger');
			if (stranger) {
				putData.source = 'NEARBY';
			}
	
			//检测并开启loading
			guigu.showLoading({
				title: '数据加载中',
				mask: true
			});
				
			$.ajax({
				url: 'https://api.svenglish.cn/api/order/course',
				type: 'PUT',
				contentType: 'application/json',
				data: JSON.stringify(putData),
				success:function(data){
					//成功
					if (data.code==1) {
						
						//拼团成功，调取支付
					//	self.pretend(data.data.orderId,putData.groupOrderId);
						location.href = 'group.html?groupOrderId=' + putData.groupOrderId;
					}else{
						//关闭loading
						guigu.hideLoading();
						guigu.showModal({
							content: data.msg,
							showCancel: false
						});
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: '请求失败，请重试！',
						showCancel: false
					});
				}
			});
		},
		pretend(orderId,groupOrderId){
			$.ajax({
				url: 'https://api.svenglish.cn/api/payment/pretend',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify({
					objectType: "COURSE",
					objectId: orderId
				}),
				success:function(data){
					//成功
					if (data.code==1) {
						location.href = 'group.html?groupOrderId=' + groupOrderId;
					}else{
						//关闭loading
						guigu.hideLoading();
						guigu.showModal({
							content: data.msg,
							showCancel: false
						});
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: '请求失败，请重试！',
						showCancel: false
					});
				}
			});
			
		},
		//拼团
		bindPintuan:function(){
			var self = this;
			if (this.groupOrderId){
				
				if (self.name == '') {
					guigu.showModal({
						content: '请填写联系人',
						showCancel: false
					});
				} else if (!/^1\d{10}$/.test(self.mobile)) {
					guigu.showModal({
						content: '请填写正确的联系电话',
						showCancel: false
					});
				} else if(!self.contactLocation){
					guigu.showModal({
						content: '请填写城市和小区名称',
						showCancel: false
					});
				} else {
						this.addGroup();
				}
				
				// else if (self.tryTime.length < 2) {
				// 	guigu.showModal({
				// 		content: '请选择2项您最方便试听的时间',
				// 		showCancel: false
				// 	});
				// } 
				
			}else{
				this.createGroup();
			}
			
			
		},

		//获取团的课程id
		getCourseId(groupOrderId){
			var self = this;


			$.ajax({
				url: 'https://api.svenglish.cn/api/order/originator?groupOrderId='+groupOrderId,
				type: 'GET',
				success:function(data){
					if (data.code == 1){
					//	var courseId = data.data.courseId;
						self.couresContactName = data.data.contactName;
						self.couresLocation = data.data.contactLocation;
						self.couresAddress = data.data.locationAddress;
						
						//设置团标题和团id
						var courseItems = self.courseItems;
						for (var i = 0; i < courseItems.length; i++) {
							if (courseItems[i].id == self.courseId) {
							//	self.courseId = courseId;
								self.courseTitle = courseItems[i].name;
								break;
							}
						}
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: '请求失败，请重试！',
						showCancel: false
					});
				}
			});

		},
		isWeiXin(){
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger'){
				return true;
			}else{
				return false;
			}
		},
		locationFocus(){
			this.showSearch = true;
			// this.$nextTick(()=>{
			// 	this.$refs.search_input.focus();
			// });
		},
		// locationKeyUp(e){
		// 	this.searchLocation(e.target.value);
		// },
		// searchLocation(keyword){
		// 	var self = this;
		// 	if(!keyword){
		// 		return;
		// 	}
		// 	$.ajax({
		// 		url: 'https://api.svenglish.cn/api/wechat/place/suggestion?region=上海&keyword='+keyword,
		// 		type: 'GET',
		// 		success:function(data){
		// 			console.log(data);
		// 			if (data.code == 1){
		// 				self.locationList = data.data;
		// 			}
		// 		}
		// 	});
		// },
		// searchListFn(data){
		// 	this.changeLocation = data;
		// 	this.showSearch = false;
		// 	this.contactLocation = data.title;
		// }
  },
  watch:{
    
  },
	mounted() {
		var self = this;

		self.courseId = this.getUrlData('courseId');

		var wxUserInfo = localStorage.getItem('wxUserInfo');
		if(wxUserInfo){
			var wxUserInfo = JSON.parse(wxUserInfo);
			this.openId = wxUserInfo.unionId;
			if(self.isWeiXin() && !self.openId) {
				location.href = 'login.html?url='+encodeURIComponent(location.href.split('#')[0]);
			}
		}else if(this.isWeiXin() && !wxUserInfo){
			location.href = 'login.html?url='+encodeURIComponent(location.href.split('#')[0]);
		}


		var urlPath = window.location.href.split('?')[0].replace(/(.+\/).*$/g, '$1'); //URL根目录
		guigu.share({
			title: '去发起1个少儿英语学习免费试听拼课--外教上门，小班拼课', // 分享标题
			desc: '针对3～12岁孩子，基于美国小学课程标准，与中国小学无缝对接', // 分享描述
			link: location.origin + '/order.html', //分享地址
			imgUrl: urlPath+'images/logo_square.png',  //分享的图片地址，需绝对路径
			success: function () { 
				
			},
			cancel: function () { 
				
			}
		});
		
		var groupOrderId = this.getUrlData('groupOrderId');
    if (groupOrderId){
			this.originator = false;
			this.groupOrderId = groupOrderId;
      //如果是加入的团，则获取课程ID，用于展示课程标题
      this.getCourseId(groupOrderId);
		}



		this.$nextTick(function(){
			// var center = new qq.maps.LatLng(39.916527,116.397128);
			// var map = new qq.maps.Map(document.getElementById('qqMap'),{
			// 		center: center,
			// 		zoom: 15
			// });
		});


		window.addEventListener('message', function(event) {
			// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
			var loc = event.data;

			if (loc && loc.module === 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
				console.log(loc);
				self.changeLocation = loc;
				self.contactLocation = loc.poiname === '我的位置' ? loc.poiaddress : loc.poiname;
				setTimeout(function(){
					self.showSearch = false;
				},300);


			}
		}, false);
		
	}
});



